package com.jvm123.api.api.controller

import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

/**
 *
 * @author yawn
 *     2019/10/3 17:35
 *
 */
@RestController
class PinyinController {

    @PostMapping(value = "pinyin")
    String pinyin(@RequestParam(required = true) String s,
                  @RequestParam(defaultValue = "true") boolean retain,
                  @RequestParam(defaultValue = " ") String separate,
                  @RequestParam(defaultValue = "0") int caseTypeNum,
                  @RequestParam(defaultValue = "0") int toneTypeNum,
                  @RequestParam(defaultValue = "0") int vTypeNum) {

        HanyuPinyinOutputFormat fmt = new HanyuPinyinOutputFormat()
        HanyuPinyinCaseType caseType = caseTypeNum == 0 ? HanyuPinyinCaseType.LOWERCASE :
                caseTypeNum == 1 ? HanyuPinyinCaseType.UPPERCASE :
                        HanyuPinyinCaseType.LOWERCASE
        HanyuPinyinToneType toneType = toneTypeNum == 0 ? HanyuPinyinToneType.WITHOUT_TONE :
                toneTypeNum == 1 ? HanyuPinyinToneType.WITH_TONE_NUMBER :
                        toneTypeNum == 2 ? HanyuPinyinToneType.WITH_TONE_MARK :
                                HanyuPinyinToneType.WITHOUT_TONE
        HanyuPinyinVCharType vType = vTypeNum == 0 ? HanyuPinyinVCharType.WITH_V :
                vTypeNum == 1 ? HanyuPinyinVCharType.WITH_U_AND_COLON :
                        vTypeNum == 2 ? HanyuPinyinVCharType.WITH_U_UNICODE :
                                HanyuPinyinVCharType.WITH_V
        fmt.setCaseType(caseType)
        fmt.setToneType(toneType)
        fmt.setVCharType(vType)
        println(new Date().toString() + " 调用接口 /pinyin，参数s=" + s)
        PinyinHelper.toHanYuPinyinString(s, fmt, separate, retain)
    }

    @ExceptionHandler
    String exHandler(Exception e) {
        "error: " + e.getMessage()
    }
}
